import axios from "axios";
// import store from '@/store/index.js';

// 设置适配器
axios.defaults.adapter = config => {
	return new Promise((resolve, reject) => {
		let settle = require('axios/lib/core/settle');
		let buildURL = require('axios/lib/helpers/buildURL');
		wx.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};
				settle(resolve, reject, response);
			}
		})
	})
}


const instance = axios.create({
	baseURL: "https://mobile.aikoolearn.com/video-dev",
	timeout: 6000,

});

let loading = false;
// 添加请求拦截器
instance.interceptors.request.use(
	function(config) {
		const token = wx.getStorageSync('Authorization');
		console.log(token, 'token-------------------------------------')
		if (token) {
			// 让每个请求携带自定义token 请根据实际情况自行修改
			config.headers = {
				"Authorization": token,
				// "Content-Type": 'application/json',

			};
		}
		return config;
	},
	function(error) {
		// 对请求错误做些什么

		const status = error.response.status;
		// switch  
		return Promise.reject(error);
	}
);

// 添加响应拦截器
instance.interceptors.response.use(

	function(response) {

		const {
			data
		} = response;
		if (response.status == 200) {
			// uni.hideLoading()
			switch (response.data.code) {
				case 401:
					wx.removeStorageSync('token');
					wx.removeStorageSync('isLogin');

					break;
				case 403:

					break;

				default:
					return Promise.resolve(response.data);
					break;
			}
			return Promise.resolve(response.data);
		}
		return response.data;

	},
	function(error) {
		uni.hideLoading()
		if (error && error.response && error.response.status) {

			switch (error.response.status) {

				case 401:
					wx.removeStorageSync('token');
					wx.removeStorageSync('isLogin');

					break;
				case 403:

					break;

				default:

					break;
			}
		}

		// 超出 2xx 范围的状态码都会触发该函数。
		// 对响应错误做点什么
		return Promise.reject(error);
	}
);

export default instance;